﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine;
using TMPro;

public class CardView : MonoBehaviour
{
    [Header("组件引用")]
    public TMP_Text nameText;
    public TMP_Text descriptionText;
    public TMP_Text energyCost;
    public SpriteRenderer imageSR;
    public GameObject wrapper;
    
    private BattleTestInitializer _battleTestInitializer;


    public string cardID { get; set; } = "";

    [Header("动画设置")]
    public float hoverScale = 1.2f;
    public float hoverMoveAmount = 7f;
    public float animationDuration = 0.2f;

    [Header("拖拽设置")]
    public float dragScale = 1.2f; // 拖拽时的缩放
    public LayerMask playAreaLayer = 1; // 可放置区域的图层

    //卡牌数据引用
    private Card _cardData;
    private Transform _transform;
    
    private Vector3 _originalPosition;
    private Vector3 _originalScale;
    private Vector3 dragStartPosition;
    private Quaternion dragStartRotation;
    private bool _isHovered = false;
    private bool _isSelected = false;
    private bool _isPlayable = true;
    private bool _isDragging = false;
    private Vector3 _dragOffset;
    private Camera _mainCamera;

    // 事件
    public System.Action<CardView> OnCardClicked;
    public System.Action<CardView> OnCardHovered;
    public System.Action<CardView> OnCardUnhovered;
    public System.Action<CardView> OnCardBeginDrag;
    public System.Action<CardView> OnCardEndDrag;
    public System.Action<CardView, Vector3> OnCardDropped; // 包含掉落位置


    private void Awake()
    {
        _transform = GetComponent<Transform>();
        _originalPosition = _transform.localPosition;
        _originalScale = _transform.localScale;

        _mainCamera = Camera.main;

        // 如果 Camera.main 为 null，尝试查找相机
        if (_mainCamera == null)
        {
            _mainCamera = FindAnyObjectByType<Camera>();
            if (_mainCamera == null)
            {
                Debug.LogError("场景中没有找到相机！");
            }
        }

        // 初始化 BattleTestInitializer
        _battleTestInitializer = FindObjectOfType<BattleTestInitializer>();
        // 确保 BattleTestInitializer 被找到
        if (_battleTestInitializer == null)
        {
            _battleTestInitializer = FindObjectOfType<BattleTestInitializer>();
            if (_battleTestInitializer == null)
            {
                Debug.LogError("CardView: 未找到 BattleTestInitializer！");
            }
        }
    }

    /// <summary>
    /// 初始化卡牌UI
    /// </summary>
    public void Initialize(Card card)
    {
        _cardData = card;
        UpdateCardDisplay();
        cardID = _cardData.id;
    }

    /// <summary>
    /// 更新卡牌显示
    /// </summary>
    public void UpdateCardDisplay()
    {
        if (_cardData == null) return;

        // 设置基础信息
        nameText.text = _cardData.name;
        descriptionText.text = _cardData.GetDescription();
        energyCost.text = _cardData.energyCost.ToString();
    }
    /// <summary>
    /// 鼠标悬停效果
    /// </summary>
    private void OnMouseEnter()
    {
        if (!_isPlayable || _isHovered) return;

        _isHovered = true;
        wrapper.SetActive(false);
        Vector3 pos = new(transform.position.x, -25, 0);
        CardViewHoverSystem.Instance.Show(_cardData, pos);
        OnCardHovered?.Invoke(this);
    }

    /// <summary>
    /// 鼠标离开效果
    /// </summary>
    private void OnMouseExit()
    {
        if (!_isPlayable || !_isHovered) return;

        _isHovered = false;
        CardViewHoverSystem.Instance.Hide();
        wrapper.SetActive(true);
        OnCardUnhovered?.Invoke(this);
    }


    /// <summary>
    /// 选择卡牌
    /// </summary>
    private void OnMouseDown()
    {
        if (!_isPlayable) return;

        _isDragging = true;
        _isSelected = true;

        wrapper.SetActive(true);
        CardViewHoverSystem.Instance.Hide();
        dragStartPosition = transform.position;
        dragStartRotation = transform.rotation;
        transform.rotation = Quaternion.Euler(0, 0, 0);
        transform.position = GetMousePositionInWorldSpace(-1);
        // 触发开始拖拽事件
        OnCardBeginDrag?.Invoke(this);
        OnCardClicked?.Invoke(this);

        Debug.Log($"正在使用{cardID}牌");

        // 停止所有动画
        StopAllCoroutines();
    }

    public  Vector3 GetMousePositionInWorldSpace(float zValue = 0f)
    {
        Camera camera = Camera.main;
        Plane dragPlane = new(camera.transform.forward, new Vector3(0, 0, zValue));
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);
        if (dragPlane.Raycast(ray, out float distance))
        {
            return ray.GetPoint(distance);
        }
        return Vector3.zero;
    }

    private void OnMouseDrag()
    {
        if (!_isDragging || !_isPlayable) return;

        // 更新卡牌位置，考虑偏移量
        transform.position = GetMousePositionInWorldSpace(-1);

    }

    private void OnMouseUp()
    {
        if (!_isDragging) return;

        _isDragging = false;

        if (Physics.Raycast(transform.position, Vector3.forward, out RaycastHit hit, 10f))
        {
            transform.position = dragStartPosition;
            transform.rotation = dragStartRotation;
        }
        else
        {
            switch (cardID)
            {
                case "strike":
                    Debug.Log("正在使用打击牌");
                    _battleTestInitializer.SimulateUseStrike(_cardData);
                    break;
                case "defend":
                    _battleTestInitializer.SimulateUseDefend(_cardData);
                    break;
                case "bash":
                    _battleTestInitializer.SimulateUseBash(_cardData);
                    break;
                default:
                    break;
            }
            transform.position = dragStartPosition;
            transform.rotation = dragStartRotation;
        }

        // 触发结束拖拽事件
        OnCardEndDrag?.Invoke(this);

        _isSelected = false;
    }



    /// <summary>
    /// 设置卡牌是否可交互
    /// </summary>
    public void SetPlayable(bool playable)
    {
        _isPlayable = playable;

    }


}

